<script setup>
import { addRolesService, allotRightsService, deleteRolesService, editRolesService, getAllRightListService, getRolesByIdService, getRolesListService, removeRightByIdService } from '@/api/user'
import { ArrowRight, Delete, Edit, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'

const rolesList = ref([])
async function getRolesList() {
  const { data: res } = await getRolesListService()
  if (res.meta.status !== 200) {
    return ElMessage.error('获取角色列表失败')
  }
  rolesList.value = res.data
  ElMessage.success('获取角色列表成功')
}
onMounted(() => {
  getRolesList()
})

const addRolesDialogVisible = ref(false)
const addRolesFormRef = ref()
const addRolesForm = ref({
  roleName: '',
  roleDesc: '',
})
const addRolesFormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
  ],
  roleDesc: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
  ],
}
function showAddRolesDialog() {
  addRolesDialogVisible.value = true
}
function addRolesDialogClosed() {
  addRolesFormRef.value.resetFields()
}
function addRoles() {
  addRolesFormRef.value.validate(async (valid) => {
    // console.log(valid)
    if (!valid)
      return
    const { data: res } = await addRolesService(addRolesForm.value)
    if (res.meta.status !== 201) {
      return ElMessage.error('添加角色失败')
    }
    ElMessage.success('添加角色成功')
    addRolesDialogVisible.value = false
    getRolesList()
    // console.log(res)
  })
}

const editRolesFormRef = ref()
const editRolesForm = ref({})
const editRolesFormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
  ],
  roleDesc: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
  ],
}
const editRolesDialogVisible = ref(false)
async function showEditDialog(row) {
  // console.log(row)

  const { data: res } = await getRolesByIdService(row.id)
  if (res.meta.status !== 200)
    return
  editRolesForm.value = res.data
  editRolesDialogVisible.value = true
}
function editRolesDialogClosed() {
  editRolesFormRef.value.resetFields()
}
function editRoles() {
  editRolesFormRef.value.validate(async (valid) => {
    if (!valid)
      return
    const { data: res } = await editRolesService(editRolesForm.value)
    if (res.meta.status !== 200) {
      return ElMessage.error('编辑信息失败')
    }

    ElMessage.success('编辑角色信息成功')
    getRolesList()
    editRolesDialogVisible.value = false
  })
}

// 删除角色
function deleteRoles(row) {
  // eslint-disable-next-line no-undef
  ElMessageBox.confirm(
    '你确定要删除吗',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      const { data: res } = await deleteRolesService(row.id)
      if (res.meta.status !== 200) {
        return ElMessage.error('删除失败')
      }
      getRolesList()

      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

function removeRightById(role, rightId) {
  // eslint-disable-next-line no-undef
  ElMessageBox.confirm(
    '此操作将永久删除该文件, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      const { data: res } = await removeRightByIdService(role.id, rightId)
      // console.log(res)
      role.children = res.data
      if (res.meta.status !== 200) {
        return ElMessage.error('删除权限失败')
      }

      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 分配权限部分
// 所有权限数据
const rightsList = ref([])
// 当前即将分配权限的角色id
const roleId = ref()
// 树形控件的属性绑定对象
const treeProps = ref({
  label: 'authName',
  children: 'children',
})
// 默认选中的节点的id值数组
const defKeys = ref([])
const setRightDialogVisible = ref(false)
const treeRef = ref()
async function showSetRightDialog(role) {
  roleId.value = role.id
  // 获取所有权限数据
  const { data: res } = await getAllRightListService('tree')
  if (res.meta.status !== 200) {
    return ElMessage.error('获取权限失败')
  }
  rightsList.value = res.data
  getLeafKeys(role, defKeys.value)
  setRightDialogVisible.value = true
}
// 通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys数组中
function getLeafKeys(node, arr) {
  // 如果当前node节点不包含children属性，则是三级节点
  // console.log(this.defKeys);
  if (!node.children) {
    return arr.push(node.id)
  }
  node.children.forEach((item) => {
    // console.log(this);
    // console.log(item);
    return getLeafKeys(item, arr)
  })
}
async function allotRights() {
  const keys = [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys(),
  ]
  const idStr = keys.join(',')
  const { data: res } = await allotRightsService(roleId.value, idStr)
  if (res.meta.status !== 200) {
    return ElMessage.error('分配权限失败')
  }
  ElMessage.success('分配权限成功')
  getRolesList()
  setRightDialogVisible.value = false
}
</script>

<template>
  <div>
    <!-- 面包屑导航区域· -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-button type="primary" @click="showAddRolesDialog">
        添加角色
      </el-button>

      <!-- 表格区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template #default="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children" :key="item1.id"
              class="bdbottom vcenter"
              :class="[i1 === 0 ? 'bttop' : '']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <el-icon><CaretRight /></el-icon>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children" :key="item2.id"
                  class="vcenter"
                  :class="[i2 === 0 ? '' : 'bdtop']"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <el-icon><CaretRight /></el-icon>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" />
        <el-table-column label="角色名称" prop="roleName" width="260" />
        <el-table-column label="角色描述" prop="roleDesc" width="260" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" @click="showEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" :icon="Delete" @click="deleteRoles(scope.row)">
              删除
            </el-button>
            <el-button type="warning" :icon="Setting" @click="showSetRightDialog(scope.row)">
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog
      v-model="addRolesDialogVisible"
      title="添加角色"
      width="50%"
      @close="addRolesDialogClosed"
    >
      <el-form ref="addRolesFormRef" :model="addRolesForm" :rules="addRolesFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addRolesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addRoles">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <el-dialog
      v-model="editRolesDialogVisible"
      title="编辑角色"
      width="50%"
      @close="editRolesDialogClosed"
    >
      <el-form ref="editRolesFormRef" :model="editRolesForm" :rules="editRolesFormRules">
        <el-form-item label="角色id" prop="roleId">
          <el-input v-model="editRolesForm.roleId" disabled />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editRolesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editRoles">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog
      v-model="setRightDialogVisible"
      title="分配权限"
      width="50%"
    >
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="allotRights">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
